package org.example.controller;

import com.google.code.kaptcha.Constants;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.example.common.lang.AjaxResult;
import org.example.common.lang.Result;
import org.example.model.User;
import org.example.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

//@RestController
//@RequestMapping("/user")
@Controller
public class LoginControllerTest {

    @Value("true")
    private boolean rememberMe;

    @Autowired
    UserService userService;

    @GetMapping("/login")
    public String login(HttpServletRequest request, HttpServletResponse response, ModelMap mmap){
//        mmap.put("isRemembered",rememberMe);
        return "demo/login";
    }

    @RequestMapping("/login")
    @ResponseBody
    public AjaxResult login(String username, String password, Boolean rememberMe, Model model, String validateCode, HttpSession session){
        System.out.println(username);
        System.out.println(password);
        System.out.println(rememberMe);
        System.out.println(validateCode);
        String captchasession = (String) session.getAttribute(Constants.KAPTCHA_SESSION_KEY);
        System.out.println(captchasession);
        if(!captchasession.equalsIgnoreCase(validateCode)){
            return AjaxResult.error("验证码错误，请点击图片刷新重新输入");
        }
        //1、获取Subject
        Subject subject = SecurityUtils.getSubject();
        //2、封装用户数据
        UsernamePasswordToken token = new UsernamePasswordToken(username,password,rememberMe);
        System.out.println("token:"+token);
        System.out.println("subject:"+subject);
        //3、执行登录操作
        try {
            System.out.println(11);
            subject.login(token);
            return AjaxResult.success();
        }catch (UnknownAccountException e){
            System.out.println(22);
            //model.addAttribute("msg","用户名不存在");
            return AjaxResult.error("用户名不存在");
        }catch (IncorrectCredentialsException e){
            System.out.println(33);
            //model.addAttribute("msg","密码错误");
            return AjaxResult.error("密码错误");
        }
    }
    @RequestMapping("/noAuth")
    public String noAuth(){
        return "error/noAuth";
    }

}
